package com.itheima.service.impl;

import com.aliyun.oss.AliyunOSS;
import com.itheima.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;

/**
 * @Author: 放学后海堤日记
 * @Date: 2023/4/14 22:51
 * @Desc:
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private AliyunOSS aliyunOSS;

    @Override
    public void download(String name, HttpServletResponse response) throws IOException {
        if (name != null) {
            URL url = new URL(name);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(url.openConnection().getInputStream());
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());

            byte[] bytes = new byte[1024];
            int len;
            while ((len = bufferedInputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, len);
            }

            bufferedInputStream.close();
            bufferedOutputStream.close();
        }
    }

    @Override
    public String upload(MultipartFile file) throws IOException {
        //指定上传到阿里云OSS的具体位置
        String dir = "reggie";
        return aliyunOSS.fileLoad(file, dir);
    }
}
